package com.sunhao.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText name;
    private EditText age;
    private EditText length;
    private EditText weight;
    private CheckBox mary;
    private Button save;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.name);
        age = findViewById(R.id.age);
        length = findViewById(R.id.length);
        weight = findViewById(R.id.weight);
        mary = findViewById(R.id.mary);
        save = findViewById(R.id.save);


        //拿到共享参数
        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);

        reload();
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取几条数据
                String mname = name.getText().toString();
                String mage = age.getText().toString();
                String mlength = length.getText().toString();
                String mweight = weight.getText().toString();
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name", mname);
                editor.putInt("age", Integer.parseInt(mage));
                editor.putFloat("length", Float.parseFloat(mlength));
                editor.putFloat("weight", Float.parseFloat(mweight));
                editor.putBoolean("mary", mary.isChecked());
                //提交数据
                editor.commit();
            }
        });
    }

    private void reload() {
        String getname = preferences.getString("name", null);
        if (getname != null) {
            name.setText(getname);
        }
        Integer getage = preferences.getInt("age", 0);
        if (getage != 0) {
            age.setText(String.valueOf(getage));
        }
        Float getlength = preferences.getFloat("length", 0f);
        if (getlength != 0f) {
            length.setText(String.valueOf(getlength));
        }
        Float getweight = preferences.getFloat("weight", 0f);
        if (getweight != 0f) {
            weight.setText(String.valueOf(getweight));
        }
        Boolean getmary = preferences.getBoolean("mary", false);
        mary.setChecked(getmary);
    }
}